import * as Joi from 'joi';
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { SequelizeModule } from '@nestjs/sequelize';

import envDBConfig from './config/env/database.config';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import envSwaggerConfig from './config/env/swagger.config';
import { getDirAllFileNameArr } from './utils/get-dir-all-file-name-arr';
import { UserModule } from './admin/user/user.module';
// import { AuthService } from './auth/auth.service';
import { AuthModule } from './auth/auth.module';
import { UserController } from './admin/user/user.controller';
import { LoggerMiddleware } from './middleware/logger.middleware';

@Module({
  imports: [
    ConfigModule.forRoot({
      encoding: 'utf-8',
      envFilePath: [...getDirAllFileNameArr()],
      expandVariables: true, // 开启嵌套变量
      ignoreEnvVars: true,
      load: [envDBConfig, envSwaggerConfig],
      validationSchema: Joi.object({
        SWAGGER_SETUP_PATH: Joi.string().default('api-docs'),
        SWAGGER_ENDPOINT_PREFIX: Joi.string().default('api/v1'),
        SWAGGER_UI_TITLE: Joi.string().default('Swagger文档标题'),
        SWAGGER_UI_TITLE_DESC: Joi.string().default('赶紧改相关配置啊~~'),
        SWAGGER_API_VERSION: Joi.string().default('1.0'),
        DB_PORT: Joi.number().default(3000),
        DB_HOST: Joi.string(),
        DB_USER: Joi.string(),
        DB_PWA: Joi.string(),
        DB_DATABASE: Joi.string(),
        DB_CONNECTION_LIMIT: Joi.number().default(10),
        SERVE_LISTENER_PORT: Joi.number().default(3000),
        HTTP_TIMEOUT: Joi.number().default(5000),
        HTTP_MAX_REDIRECTS: Joi.number().default(5),
        NODE_ENV: Joi.string()
          .valid('development', 'production', 'test', 'provision')
          .default('development'),
      }),
      validationOptions: {
        allowUnknown: false, // 控制是否允许环境变量中位置的键，默认为true
        abortEarly: true, // 默认为false, 改为true 后，在遇到第一个错误时就停止验证，默认false,会返回所有错误
      },
    }),
    SequelizeModule.forRoot({
      dialect: 'mysql',
      host: process.env.DB_HOST,
      port: parseInt(process.env.DB_PORT, 10),
      username: process.env.DB_USER,
      password: process.env.DB_PWA,
      database: process.env.DB_DATABASE,
      models: [],
    }),
    UserModule,
    AuthModule,
  ],
  controllers: [AppController, UserController],
  providers: [AppService],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(LoggerMiddleware).forRoutes('*');
  }
}
